package myJs.user.soft

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.{BootstrapValidator, LayerOptions}
import myJs.myPkg.jquery._
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.soft.fileSelect._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._
import shared.Pojo.VarInfoDataKind

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("Venn")
object Venn {
  val formId = "form"
  val fileModalId = "fileModal"
  val tableId = "table"
  val timeFieldNames = List[String]()

  val curSoft = Tool.kindSoftFMap(VennSoft.nameStr)

  @JSExport("init")
  def init = {
    FileModal.init
    registerEvent

    bootStrapValidator
    $("#form").bv.revalidateField("missionName")
    Tool.refreshCalculateConfig { rs =>
      val labels = rs("labels").split(":")
      val fileNames = rs("diffFiles").split(":")
      labels.zip(fileNames).foreach { case (labelStr, fileName) =>
        addDiffFile(labelStr = labelStr, fileName = fileName)
      }
    }
    if (Tool.getMissionId.isEmpty) {
      refreshDiffFile
    }
    VideoCp.Props(soft=VennSoft).render.renderIntoDOM(document.querySelector("#videoRoot"))

    //    fileSelectShow
    //    $("#groupFile").show()

  }

  def refreshDiffFile = {
    (1 to 2).foreach { i =>
      addDiffFile()
    }
  }

  def addDiffFile(labelStr: String = "", fileName: String = "") = {
    val html = div(`class` := "eachDiffFile",
      div(`class` := "form-group ",
        label(`class` := "control-label col-sm-2", s"${messages("labelInPlot")}:"),
        div(`class` := "col-sm-3",
          input(`type` := "text", `class` := "form-control fillByName", value := s"${labelStr}",
            name := "labels[]")
        ),
      ),
      div(`class` := "form-group",
        label(`class` := "control-label col-sm-2", s"${messages("list")}:"),
        div(`class` := "col-sm-4",
          input(`type` := "text", `class` := "form-control fillByName  myFile", value := s"${fileName}",
            name := "diffFiles[]", readonly)
        ),
        div(`class` := "col-sm-3",
          button(`type` := "button", `class` := "btn green myFileSelect",
            dataValue := s"missionResult;${VarInfoDataKind.name};example", dataInputName := "diffFile",
            dataMissionKind := s"${OplsdaSoft.nameStr},${DiffAnaSoft.nameStr},${DiffAnaMulSoft.nameStr}",
            dataFileName:="demo_for_venn_1.txt;demo_for_venn_2.txt",
            span(`class` := "fa fa-file"), " ",messages("selectFile")),
          button(`type` := "button", `class` := "btn btn-default deleteButton",marginLeft:=5,
            span(`class` := "fa fa-trash"), " ",messages("delete"))
        )
      )
    )

    $("#diffFiles").append(html.render)
    setDisable
    val bv = $("#form").bv
    val fieldNames = List("diffFiles[]", "labels[]")
    fieldNames.foreach { fieldName =>
      val jq = $(s".eachDiffFile:last-child").findInputByName(fieldName)
      bv.addField(jq).revalidateField(jq)
    }

  }

  def setDisable = {
    val size = $(".eachDiffFile").mapElems(y => y).size
    size match {
      case x if x <= 2 =>
        $(".deleteButton").setDisabled(true)
      case x if x > 2 =>
        $(".deleteButton").setDisabled(false)
    }
  }

  def registerEvent = {
    $(document.body).on("click", ".myRun", "", (y: Element) => {
      myRun
    })
    $(document.body).on("click", ".myFileSelect", "", (y: Element) => {
      val lis = $(y).dataValue.split(";")
      $(".myFileSelect").removeClass("myCurrent")
      $(y).addClass("myCurrent")
      FileModal.fileSelectShow(lis)
    })

    $(document.body).on("click", ".myFileSelectButton", "", (y: Element) => {
      val folder = $(y).dataFolder
      val fileName = $(y).dataFileName
      Tool.fileSelect(folder, fileName)
      val inputJq = $(".myFileSelect.myCurrent").parent().parent().prev().find("input")
      val names = folder.split("/")
      val defaultLabel = if (names(0) == "mission") {
        folder.split("/")(1)
      } else {
        fileName.fileNamePrefix
      }
      inputJq.`val`(s"${defaultLabel}")
      $("#form").bv.revalidateField(inputJq)
    })
    $(document.body).on("click", s".myAddDiffFile", "", (y: Element) => {
      addDiffFile()
    })
    $(document.body).on("click", s".deleteButton", "", (y: Element) => {
      deleteDiffFile(y)
    })

  }

  def deleteDiffFile(y: Element) = {
    $(y).parents(".eachDiffFile").remove()
    $(s"#form").bv.revalidateField("diffFiles[]").revalidateField("labels")
    setDisable
  }

  @JSExport("myRun")
  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.SoftController.analysis().url.toString
      val formData = $(s"#form").serialize()
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${curSoft.nameStr}",
        headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          window.location.href = g.jsRoutes.controllers.MissionController.missionManageBefore().url.toString
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {

    def differentF: js.Function = (value: String, bv: BootstrapValidator, jq: JQuery) => {
      val vElemsMap = Tool.getInputByName("labels[]").mapElems(y => y).map { y =>
        val v = $(y).myVal
        v -> y
      }.filter { case (v, y) =>
        v.nonBlank
      }.groupMap(_._1)(_._2)
      vElemsMap.foreach { case (v, ys) =>
        if (ys.size > 1) {
          ys.foreach { y =>
            bv.updateStatus($(y), "INVALID", "blank")
          }
        } else {
          ys.foreach { y =>
            bv.updateStatus($(y), "VALID", "blank")
          }
        }
      }
      true
    }

    val url = g.jsRoutes.controllers.MissionController.missionNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "missionName" ->{
          val info=messages("taskName")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("exist")}",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000,
              ),
            )
          )
        },
        "file" -> {
          val info = messages("dataMatrix")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "diffFiles[]" -> {
          val info = messages("list")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "labels[]" -> {
          val info = messages("labelInPlot")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "callback" -> js.Dictionary(
                "callback" -> differentF
              ),
              "blank" -> js.Dictionary(
                "message" -> s"${messages("notSame",info)}！"
              )
            )
          )
        },

      )
    )
    $(s"#form").bootstrapValidator(dict)
  }


}
